package com.etogc.groupchat.login.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.etogc.groupchat.R;
import com.etogc.groupchat.base.BaseActivity;
import com.etogc.groupchat.common.CommonSp;
import com.etogc.groupchat.common.WebActivity;
import com.etogc.groupchat.login.biz.LoginBiz;
import com.etogc.groupchat.login.biz.LoginHttpBiz;
import com.etogc.util.GcUrl;
import com.etogc.util.IntentHelper;
import com.etogc.util.YcToastHelper;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.TextMessage;

public class LoginActivity extends BaseActivity {

    private EditText etName;
    private EditText etPwd;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        etName = findViewById(R.id.etName);
        etPwd = findViewById(R.id.etPwd);
        etName.setText(CommonSp.getPhone());
        findViewById(R.id.btnLogin).setOnClickListener(listener);
        findViewById(R.id.tvForget).setOnClickListener(listener);
        findViewById(R.id.tvWx).setOnClickListener(listener);
        findViewById(R.id.tv_user_intro).setOnClickListener(listener);
        setTitle("登录");
        showBack();
//        test();
    }

    private void test() {
//        etName.setText("13655013132");
//        etPwd.setText("123456");
//        etName.setText("18649864289");
//        etPwd.setText("abc123");
        etName.setText("15306912374");
        etPwd.setText("123456");
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btnLogin:
                    requestLogin();
                    break;
                case R.id.tvForget:
                    jumpForget();
                    break;
                case R.id.tvWx:
                    jumpWx();
                    break;

                case R.id.tv_user_intro:
                    jumpWeb();
                    break;
            }

        }
    };


    //需要服务端返回token
    private void requestLogin() {
        String name = etName.getText().toString();
        String pwd = etPwd.getText().toString();

        if (LoginBiz.checkLogin(name, pwd)) {
//            String token = testGetToken(name);
//            LoginHttpBiz.connect_rong(this, token);
            LoginHttpBiz.login(this, name, pwd, "mobile");
        }
    }

    private String testGetToken(String name) {
        String token1 = null;
        if ("123".equals(name)) {
            token1 = "2bDhoSZj7B21zI3I96vdW7lE6cwVy6v6WvXUJ49E/RmZbEpZ1JqcJsdFoJAYDMWIVfm07xUb0tE=";
        } else if ("456".equals(name)) {
            token1 = "C0RDrmnDsb4cdpQk6qqyh7lE6cwVy6v6WvXUJ49E/RmZbEpZ1JqcJmsb+BHEol8UePwcm+Smy2I=";
        } else if ("111".equals(name)) {
            token1 = "UtYAKMKUzAMcdpQk6qqyh7lE6cwVy6v6WvXUJ49E/RmZbEpZ1JqcJl6yEuqN47EQ2y083wMJysI=";
        } else if ("222".equals(name)) {
            token1 = "yT90jgO0in4cdpQk6qqyh7lE6cwVy6v6WvXUJ49E/RmZbEpZ1JqcJjnhtQpZpNuJkkxpYCGzZYU=";
        }
        return token1;
    }


    private void jumpForget() {
        IntentHelper.getInstances().getIntent(this, ForgetActivity.class);
    }

    private void jumpWx() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this, mPermissionList, 123);
        }

        UMShareAPI.get(this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
    }

    private void jumpWeb() {
        String url = GcUrl.HOST + "/static/agreement.html";
        if (url != null) {
            Intent intent = new Intent(this, WebActivity.class);
            intent.putExtra("url", url);
            intent.putExtra("title", "用户协议");
            startActivity(intent);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

    }

    private UMAuthListener authListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            if (data != null) {
                String open_id = data.get("openid");
                String name = data.get("name");
                String iconurl = data.get("iconurl");
                LoginHttpBiz.loginWX(LoginActivity.this, open_id, name, iconurl, "wx");
            } else {
                YcToastHelper.getInstance()._toast("登录失败");
            }
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            YcToastHelper.getInstance()._toast("登录失败" + t.getMessage());
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            YcToastHelper.getInstance()._toast("登录取消");
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);//完成回调
    }

    private void sendMsg() {
        TextMessage txtMsg = TextMessage.obtain("fuck you");
        RongIMClient.getInstance().sendMessage(Conversation.ConversationType.PRIVATE, "456", txtMsg, null, null, new IRongCallback.ISendMediaMessageCallback() {
            @Override
            public void onProgress(Message message, int i) {
                Log.e("sendMsg", "onProgress");
            }

            @Override
            public void onCanceled(Message message) {
                Log.e("sendMsg", "onCanceled");
            }

            @Override
            public void onAttached(Message message) {
                Log.e("sendMsg", "onAttached");
            }

            @Override
            public void onSuccess(Message message) {
                Log.e("sendMsg", "onSuccess");
            }

            @Override
            public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                Log.e("sendMsg", "onError=" + String.valueOf(message) + ",code=" + String.valueOf(errorCode.getValue()));
            }
        });
    }

}
